package com.soundai.skill.helloworld.test;

import redis.clients.jedis.Jedis;

import java.util.Iterator;
import java.util.Set;

public class clearRedis {

    static Jedis js = null;
    //public static Logger logger = Logger.getLogger(RedisDBHelper.class);
    private static String hostUrl = "localhost";//BaseInfo.getInfo("hostUrl");
    private static int hostPort = 6379;//Integer.parseInt(BaseInfo.getInfo("hostPort"));
    private static String authPassWord = "root";//BaseInfo.getInfo("authPassWord");

    /**
     * 链接redis数据库，进行初始化
     *
     * @return：返回是否初始化链接成功
     */
    public static boolean init() {
        if (js == null) {
            js = new Jedis(hostUrl, hostPort);
            js.auth(authPassWord);
        }
        if (js != null) {
           // logger.info("初始化成功");
            return true;
        } else {
            return false;
        }
    }


    /**
     * 删除数据
     *
     * @param key：要删除数据的key
     * @return：返回boolean值，表示是否删除成功
     */
    public static boolean delete(String key) {
        if (js.exists(key)) {
            if (js.del(key) == 1) {
               // logger.info("删除数据成功");
                return true;
            } else {
                //logger.info("删除数据失败");
                return false;
            }
        } else {
            //logger.info(key + "不存在");
            return false;
        }
    }


    /**
     * 按照关键字删除redis缓存数据
     */
    public static void deleteData(String keys) {
        //链接redis数据库，进行初始化
        init();
        Set<String> set = js.keys("*");
        if (set.size() != 0) {
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (key.contains(keys)) {

                    delete(key);
                }
            }
        } else {
            //logger.info("数据库暂时没有数据");
        }
        //关闭链接
        unInit();
    }


    /**
     * 关闭链接
     */
    public static void unInit() {
        if (js != null) {
            js.close();
            js = null;
        }
    }
    public  static  void main(String[] args) {
        deleteData("key");
    }



}
